package com.beyondsoft.dtc.mobile.automation.manage;

import com.beyondsoft.dtc.mobile.automation.base.GlobalConstants;
import com.beyondsoft.dtc.mobile.automation.util.ShellUtil;
import com.beyondsoft.dtc.mobile.automation.util.StringUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

@Deprecated
public class ThreadPoolManager {

    private static ThreadPoolManager manager = null;

    // private ExecutorService executorService;
    private ThreadPoolExecutor executorService;
    private List<Future<String>> resultList = new ArrayList<Future<String>>();

    private ThreadPoolManager() {
        int num = Runtime.getRuntime().availableProcessors();
        // LogUtil.e(LogUtil.TAG, "num:" + num);
        // executorService = Executors.newFixedThreadPool(num * 4);
        // threadPoolExecutor = Executors.newFixedThreadPool(num * 4);
        // 构造一个线程池
        executorService = new ThreadPoolExecutor(2, 4, 3, TimeUnit.SECONDS,
                new ArrayBlockingQueue<Runnable>(3),
                new ThreadPoolExecutor.DiscardOldestPolicy());
    }

    public static synchronized ThreadPoolManager getInstance() {
        if (manager == null) {// 懒汉式
            manager = new ThreadPoolManager();
        }
        return manager;
    }

    public String getPollCount() {
        return executorService.getActiveCount() + " "
                + executorService.getCompletedTaskCount();
    }

    public void addTask(Callable<String> callable) {
        Future<String> future = executorService.submit(callable);
        // 将任务执行结果存储到List中
        resultList.add(future);
    }

    public void shutdown() {

        executorService.shutdown(); // Disable new tasks from being submitted
        try {
            // Wait a while for existing tasks to terminate
            if (!executorService.awaitTermination(60, TimeUnit.SECONDS)) {
                executorService.shutdownNow(); // Cancel currently executing
                // tasks
                // Wait a while for tasks to respond to being cancelled
                if (!executorService.awaitTermination(60, TimeUnit.SECONDS))
                    System.err.println("Pool did not terminate");
            }
        } catch (InterruptedException ie) {
            // (Re-)Cancel if current thread also interrupted
            executorService.shutdownNow();
            // Preserve interrupt status
            Thread.currentThread().interrupt();
        }
    }

    public List<Future<String>> getResultList() {
        return resultList;
    }

    /**
     * 获取当前还没有执行线程
     *
     * @param devices
     * @return
     */
    public List<Future<String>> getCurrentNotOverThread() {
        List<Future<String>> notOverfutures = new ArrayList<Future<String>>();
        int i = 0;
        for (; i < resultList.size(); i++) {
            try {
                resultList.get(i).get(50, TimeUnit.MILLISECONDS);

            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            } catch (TimeoutException e) {
                // e.printStackTrace();
                notOverfutures.add(resultList.get(i));
            }
        }
        return notOverfutures;
    }

    public static void main(String[] args) {
        String ss = "8.6% 20211/fm.qingting.qtradio: 6.9% user + 1.6% kernel / faults: 20338 minor 8 major\n" +
                "  0.3% 20338/fm.qingting.qtradio:local: 0% user + 0.3% kernel / faults: 512 minor";
		String as = "3588  1  34% S    33 353688K  91936K  fg app_67   fm.qingting.qtradio\n" +
                " 3625  1   0% S    14 294028K  43768K  bg app_67   fm.qingting.qtradio:hotFix\n" +
                " 3729  1   0% R     9 277208K  37788K  fg app_67   fm.qingting.qtradio:local";
//		String  ss = "21702  7 0  11% S    38 1456528K 110236K  fg u0_a1046 com.shuiguolianliankan";
		String ret = as.replaceAll("\\s{2,}",
				GlobalConstants.SYMBOL_SPACE).trim(); // remove multiple blank space.
		String[] results = ret.split(GlobalConstants.SYMBOL_SPACE);
        String cpuUseString = results[2].contains(GlobalConstants.SYMBOL_PCT) ? results[2] : results[3];

        double cpuPercent = Double.valueOf(cpuUseString.trim()
				.replace(GlobalConstants.SYMBOL_PCT, "")
				.replace(GlobalConstants.SYMBOL_PLUS, "")
				.replace(GlobalConstants.SYMBOL_DASH, ""));
		 System.out.println(cpuPercent);
//        String ret = ss.replaceAll("\\s{2,}",
//                GlobalConstants.SYMBOL_SPACE).trim(); // remove multiple blank space.
//        String[] results = ret.split(GlobalConstants.SYMBOL_SPACE);
//        if (results.length > 0) {
//            double cpuPercent = 0;
//            try {
//                String replace = results[0].trim()
//                        .replace(GlobalConstants.SYMBOL_PCT, "")
//                        .replace(GlobalConstants.SYMBOL_PLUS, "")
//                        .replace(GlobalConstants.SYMBOL_DASH, "");
//                cpuPercent = Double.valueOf(replace);
//            } catch (NumberFormatException e) {
//                System.out.println(e.getMessage());
//            }
//            System.out.println("cpuPercent" + cpuPercent);
//        }
//		String[] command = new String[]{
//				"sh",
//				"-c",
//				"adb"
//						+ " -s "
//						+ "12d757b6"
//						+ " shell 'cat /proc/net/xt_qtaguid/stats'"
//						+ " | grep "
//						+ 10154  + " |grep -E 'wlan0|rmnet0'"
//						+ " | gawk 'BEGIN {recv=0;sent=0;} {recv+=$6;sent+=$8;} END{print recv,sent;}'"};
//
//		ShellUtil.CommandResult commandResult = ShellUtil.execCommand(command);
//		if (commandResult.isCommandSucceeded()
//				&& !StringUtil.isEmpty(commandResult.getResultMsg())) {
//			String[] data = commandResult.getResultMsg().split(
//					GlobalConstants.SYMBOL_SPACE);
//
//		}
    }

}
